package com.sparrow.socket.tcp.codec;

import com.sparrow.socket.util.CodecUtil;
import com.sparrow.socket.util.PacketHelper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class VerifyDecoder extends MessageToMessageDecoder<ByteBuf> {

    private static Logger logger = LoggerFactory.getLogger(VerifyDecoder.class);

    private static final short MAGIC = (short) 0x1A2B;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        short magic = byteBuf.readShort();
        if (magic != MAGIC) {
            logger.error("[安全警告] 非法连接 Magic 校验失败，来自: {}" , ctx.channel().remoteAddress());
            ctx.close();
            return;
        }
        //引用计数+1 还需要传递给RequestDecoder 处理。
        //不加引用的话 这个decode结束就会释放了bytebuf,传递给下一个decoder就会报错了
        byteBuf.retain();
        //要加到out里面 才会传递给下个MessageToMessageDecoder
        out.add(byteBuf);
    }
}
